package com.freejava.test_roles.service;

import com.freejava.test_roles.entity.User;
import com.freejava.test_roles.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.getUserByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("该账户不存在");
        }

        // 根据user id获取用户的角色信息
        user.setRoles(userMapper.getUserRoleByUserId(user.getId()));
        return user;
    }
}
